import React, { useRef, useLayoutEffect } from 'react'
import styles from './index.module.scss'

function Affix ({ children }) {
  const placeholderRef = useRef()
  const contentRef = useRef()

  const onScroll = () => {
    const { top } = placeholderRef.current.getBoundingClientRect()

    if (top <= 0) {
      contentRef.current.classList.add(styles.fixed)
      placeholderRef.current.style.height = '40px'
    } else {
      contentRef.current.classList.remove(styles.fixed)
      placeholderRef.current.style.height = '0px'
    }
  }

  useLayoutEffect(() => {
    window.addEventListener('scroll', onScroll)

    return () => {
      window.removeEventListener('scroll', onScroll)
    }
  }, [])

  return (
    <div>
      {/* 占位视图 */}
      <div ref={placeholderRef}></div>
      {/* 内容视图 */}
      <div ref={contentRef}>{children}</div>
    </div>
  )
}

export default Affix
